# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log


class JdmzDBPipeline(object):
    def __init__(self):
        client = pymongo.MongoClient(
            settings["MONGODB_SERVER"],
            settings["MONGODB_PORT"]
        )
        db = client[settings['MONGODB_DB']]
        self.collection = db[settings['MONGODB_COLLECTION']]

    def process_item(self, item, spider):
        valid = True
        for data in item:
            if not data:
                valid = False
                raise DropItem("Mission {0}!".format(data))
        if valid:
            self.collection.insert(dict(item))
            log.msg("Meizi added to MongoDB database!", level = log.DEBUG, spider=spider)

        return item

class DuplicatesPipeline(object):
    def __init__(self):
        self.imgs_seen = set()

    def process_item(self, item, spider):
        if item['datasrc'] in self.imgs_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.imgs_seen.add(item['datasrc'])
            return item